<template>
  <div>
    <el-row align="middle" class="pt-20">
      <el-col :span="16">
        <p class="main_title">{{ $t('menu.WEB') }}</p>
      </el-col>
    </el-row>
    <div style="display: flex; margin: 15px;0;15px;0">
      <div style="flex: 0 0 70%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-row class="search_block pt-20">
          <el-col :span="8">
            <el-input placeholder="请输入网站名称\URL" v-model="searchData.term" class="input-with-select" clearable
              @change="doList">
              <el-button slot="append" icon="el-icon-search" @click="doList">查询</el-button>
            </el-input>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="table_container">
      <el-table :data="webs" :header-cell-style="boxheader" :row-style="{height:0+'px'}" :cell-style="{padding:0+'px'}"
        style="width: 100%">
        <el-table-column min-width="40px" align="center" :label="$t('web.WEBID')" prop="webid">
          <template slot-scope="scope">
            <span>{{ scope.row.webid}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="80px" align="center" :label="$t('web.WEBNAME')">
          <template slot-scope="scope">
            <span>{{ scope.row.webname}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="120px" align="center" :label="$t('web.WEBURL')">
          <template slot-scope="scope">
            <span>{{ scope.row.weburl}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="120px" align="center" :label="$t('web.FIRSTURL')">
          <template slot-scope="scope">
            <span>{{ scope.row.firstpage}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="70px" align="center" :label="$t('web.CATCH')" prop="period">
          <template slot-scope="scope">
            <span>{{ scope.row.period}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="70px" align="center" :label="$t('web.FREQUENCY')" prop="frequency">
          <template slot-scope="scope">
            <span>{{ scope.row.frequency}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="40px" align="center" :label="$t('web.STATUS')" prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0" class="priority_middle">{{  $t('status.REGULAR') }}</span>
            <el-tag type="danger" effect="dark" v-if="scope.row.status == 1">{{ $t('status.EXPIRE')}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column min-width="60px" align="center" label="主机">
          <template slot-scope="scope">
            <span>{{ scope.row.hostname }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="100px" align="center" :label="$t('common.OPER')" v-if="userStat === 1">
          <template slot-scope="scope">
            <el-button style="margin-left:0px !important;" type="text"
              @click="updateWeb(scope.$index, scope.row)">{{ $t('common.UPDATE') }}</el-button>
            <el-button style="margin-left:0px !important;" v-if="scope.row.status == 0" type="text"
              @click="expire(scope.row)">{{ $t('common.EXPIRE') }}</el-button>
            <el-button style="margin-left:0px !important;" v-if="scope.row.status == 1" type="text"
              @click="active(scope.row)">{{ $t('common.ACTIVE') }}</el-button>
            <el-button style="margin-left:0px !important;" type="text"
              @click="configWeb(scope.$index, scope.row)">白名单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="col-sm pt-3 text-sm-left" style="text-align:right; display: contents">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchData.curpage" :page-sizes="[5, 10, 20, 50]" :page-size="searchData.pagesize"
          layout="total, sizes,  pager, jumper" :total="searchData.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="$t('button.UPDATEWEB')" :visible.sync="updateVisible" :width="width"
      :close-on-click-modal="false" class="addQuestion">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <el-form :model="updateform" :rules="rules" ref="updateform" label-width="140px">
        <el-form-item :label="$t('web.WEBNAME')" prop="webname">
          <el-input v-model="updateform.webname" :placeholder="$t('tips.ENTER.WEBNAME')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('web.WEBURL')" style="clear:both" prop="weburl">
          <el-input v-model="updateform.weburl" :placeholder="$t('tips.ENTER.WEBURL')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('web.FIRSTURL')" style="clear:both" prop="firstpage">
          <el-input v-model="updateform.firstpage" :placeholder="$t('tips.ENTER.FIRSTURL')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('web.CATCH')" style="clear:both" prop="period">
          <el-input v-model="updateform.period" :placeholder="$t('tips.ENTER.PERIOD')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('web.FREQUENCY')" style="clear:both" prop="frequency">
          <el-input v-model="updateform.frequency" :placeholder="$t('tips.ENTER.FERQUENCY')"></el-input>
        </el-form-item>
        <!--<el-form-item :label="$t('web.STATUS')" style="clear:both" prop="status">-->
        <!--<el-radio-group v-model="updateform.status">-->
        <!--<el-radio label="0">{{$t('status.REGULAR')}}</el-radio>-->
        <!--<el-radio label="1">{{$t('status.EXPIRE')}}</el-radio>-->
        <!--</el-radio-group>-->
        <!--</el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align:center!important;">
        <el-button class="cancel_button" @click="updateCancel('updateform')">{{ $t('common.CANCEL') }}</el-button>
        <el-button class="confirm_button" @click="updateSubmit('updateform')">{{ $t('common.CONFIRM2') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog title="公棚清单（未配置则抓取所有）" :visible.sync="configVisible" :width="width" :close-on-click-modal="false"
      class="addQuestion">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <el-tag :key="tag" v-for="tag in orgnameList" closable :disable-transitions="false" @close="handleClose(tag)">
        {{tag}}
      </el-tag>
      <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
        @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">添加公棚</el-button>
      <span slot="footer" class="dialog-footer" style="text-align:center!important;">
        <el-button class="cancel_button" @click="configCancel('updateform')">{{ $t('common.CANCEL') }}</el-button>
        <el-button class="confirm_button" @click="configSubmit('updateform')">{{ $t('common.CONFIRM2') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import webService from "@/service/webService";
import enlargeImg from "@/assets/images/icon_2.png";
import narrowImg from "@/assets/images/icon_3.png";
import i18n from "@/lang";
import { mapGetters } from "vuex";

export default {
  name: "WebList",
  data() {
    return {
      boxheader: {
        // background: '#eef1f6',
        color: "#606266",
        fontWeight: 800,
        borderBottom: "2px solid #EBEEF5",
      },
      searchData: {
        term: "",
        curpage: 1,
        pagesize: 10,
      },
      webs: [],
      total: 0,
      iconImg: enlargeImg,
      width: "600px",
      updateVisible: false,
      updateform: {
        webname: "",
        weburl: "",
        firstpage: "",
        period: "",
        frequency: "",
        status: "",
      },
      updaterId: "",
      configVisible: false,
      configId: "",
      orgnameList: [],
      inputVisible: false,
      inputValue: "",
      rules: {
        webname: [
          {
            required: true,
            message: i18n.t("valid.WEBNAME.NOTNULL"),
            trigger: "blur",
          },
          {
            max: 20,
            message: i18n.t("valid.WEBNAME.SIZELIMIT"),
            trigger: "blur",
          },
        ],
        weburl: [
          {
            required: true,
            message: i18n.t("valid.WEBURL.NOTNULL"),
            trigger: "blur",
          },
          {
            max: 100,
            message: i18n.t("valid.WEBURL.SIZELIMIT"),
            trigger: "blur",
          },
        ],
        firstpage: [
          {
            required: true,
            message: i18n.t("valid.FIRSTURL.NOTNULL"),
            trigger: "blur",
          },
          {
            max: 100,
            message: i18n.t("valid.FIRSTURL.SIZELIMIT"),
            trigger: "blur",
          },
        ],
        period: [
          {
            required: true,
            message: i18n.t("valid.PREIOD.NOTNULL"),
            trigger: "blur",
          },
        ],
        frequency: [
          {
            required: true,
            message: i18n.t("valid.FREQUENCY.NOTNULL"),
            trigger: "blur",
          },
        ],
        status: [],
      },
    };
  },
  watch: {},
  mounted: function () {
    // commit('SET_ACTIVE', 4)
    this.$store.dispatch("setActive", "4").then(() => {
      // this.$root.eventBus.$emit('exit')
    });
    // localStorage.setItem('active', 4)
    webService.listWebs({ curpage: 1, pagesize: 10 }).then((res) => {
      if (res && res.data.result === 0) {
        this.webs = res.data.data;
        this.searchData.total = res.data.total;
      }
    });
  },
  created() {},
  destroyed() {},
  computed: {
    ...mapGetters(["userid", "userStat"]),
  },
  methods: {
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("/")[0]),
        h("br"),
        h("span", {}, column.label.split("/")[1]),
      ]);
    },
    updateWeb(index, row) {
      this.updaterId = row.webid;
      this.updateVisible = true;
      this.updateform = {
        webname: row.webname,
        weburl: row.weburl,
        firstpage: row.firstpage,
        period: row.period,
        frequency: row.frequency,
        status: String(row.status),
      };
    },
    updateCancel() {
      this.updateVisible = false;
      this.updaterId = "";
    },
    updateSubmit(updateform) {
      this.$refs[updateform].validate((valid) => {
        let dataInfo = {};
        dataInfo.webid = this.updaterId;
        if (!this.ifnull(this.updateform.webname)) {
          dataInfo.webname = this.updateform.webname;
        }
        if (!this.ifnull(this.updateform.weburl)) {
          dataInfo.weburl = this.updateform.weburl;
        }
        if (!this.ifnull(this.updateform.firstpage)) {
          dataInfo.firstpage = this.updateform.firstpage;
        }
        if (!this.ifnull(this.updateform.period)) {
          dataInfo.period = this.updateform.period;
        }
        if (!this.ifnull(this.updateform.frequency)) {
          dataInfo.frequency = this.updateform.frequency;
        }
        if (!this.ifnull(this.updateform.status)) {
          dataInfo.status = this.updateform.status;
        }
        if (valid) {
          webService.updateWeb(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                message: i18n.t("tips.WEB.UPDATESUCCESS"),
                type: "success",
              });
              this.updateVisible = false;
              this.listWeb();
            }
          });
        } else {
          return false;
        }
      });
    },

    configWeb(index, row) {
      this.configId = row.webid;
      this.configVisible = true;
      this.orgnameList = this.ifnull(row.orgname) ? [] : row.orgname.split(",");
    },
    configCancel() {
      this.configVisible = false;
      this.configId = "";
    },
    configSubmit() {
      let dataInfo = {};
      dataInfo.webid = this.configId;
      dataInfo.orgname = this.orgnameList.join(",");
      webService.updateWeb(dataInfo).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: i18n.t("tips.WEB.UPDATESUCCESS"),
            type: "success",
          });
          this.configVisible = false;
          this.listWeb();
        }
      });
    },
    handleClose(tag) {
      this.orgnameList.splice(this.orgnameList.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.orgnameList.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    expire(row) {
      this.$confirm("是否设置网站 " + row.webname + " 失效?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let dataInfo = {
            webid: row.webid,
            status: "1",
          };
          webService.updateWeb(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                type: "success",
                message: "设置失效成功!",
              });
              this.listWeb();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消设置",
          });
        });
    },
    active(row) {
      this.$confirm("是否上线网站 " + row.webname + " ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let dataInfo = {
            webid: row.webid,
            status: "0",
          };
          webService.updateWeb(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                type: "success",
                message: "网站上线成功!",
              });
              this.listWeb();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消设置",
          });
        });
    },

    ifnull(data) {
      if (data == null || data == undefined || data == "") {
        return true;
      } else {
        return false;
      }
    },
    /**
     * 弹窗放大缩小
     */
    enlarge() {
      if (this.width === "600px") {
        this.width = "1000px";
        this.iconImg = narrowImg;
      } else {
        this.width = "600px";
        this.iconImg = enlargeImg;
      }
    },
    /**
     * 改变分页大小
     * @param val 分页大小
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchData.pagesize = val;
      console.log(this.searchData.pagesize, "this.searchData.pagesize");
      this.listWeb();
    },
    /**
     * 选择页码
     * @param val 当前页码
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchData.curpage = val;
      console.log(this.searchData.curpage, "this.searchData.curpage");
      this.listWeb();
    },
    doList() {
      this.searchData.curpage = 1;
      this.listWeb();
    },
    listWeb() {
      webService.listWebs(this.searchData).then((res) => {
        if (res && res.data.result === 0) {
          this.webs = res.data.data;
          this.searchData.total = res.data.total;
        }
      });
    },
  },
};
</script>

<style>
.main_title {
  color: #343434;
  font-size: 18px;
  margin: 7px 0 0 0;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
